package com.rocker.graduation.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import com.rocker.graduation.constants.Constants;
import com.rocker.graduation.domain.Category;
import com.rocker.graduation.service.IImageService;
import com.rocker.graduation.util.BaseUtils;

@Controller
@RequestMapping("/image")
public class ImageController {
	@Autowired
	private IImageService imageService;
	
	
	
	@RequestMapping(value="/getImage.action/{imageId}")
	public void getImage(HttpServletRequest request, HttpServletResponse response, @PathVariable String imageId){
		String path = request.getSession().getServletContext().getRealPath("/");
		response.setContentType("image/jpg");
		try {
			byte[] data = imageService.getByteArray(imageId).getEntity();
			BufferedImage bImage = BaseUtils.markImageLogo(data, path);
			ImageIO.write(bImage, "JPEG", response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping("/test")
	public ModelAndView test(){
		ModelAndView modelAndView = new ModelAndView();
		imageService.test();
		
		return modelAndView;
	}
	
	@RequestMapping("/saveEntity.action")
	public ModelAndView saveEntity(@RequestBody Category category){
		ModelAndView mav = new ModelAndView();
		MappingJackson2JsonView jsonView = new MappingJackson2JsonView();
		Map<String, Object> attributes = new HashMap<String, Object>();
		boolean isSuccess = imageService.saveEntity(category);
		if (isSuccess) {
			attributes.put(Constants.ERROR, Constants.SUCCESS);
		}else {
			attributes.put(Constants.ERROR, Constants.FAILED);
		}
		jsonView.setAttributesMap(attributes);
		mav.setView(jsonView);
		return mav;
	}
}
